package com.sa.token.handler;

import com.sa.token.entity.SysLoginLogEntity;
import com.sa.token.mapper.SysLoginLogMapper;
import com.sa.token.utils.AddressUtils;
import com.sa.token.utils.IpUtils;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @desc: 使用Spring的@Async异步注解+线程池创建多线程
 * @projectName: sa-token-serve
 * @author: xhs
 * @date: 2021/12/29 14:24
 * @version: JDK 1.8
 */
@Slf4j
@Component
public class LoginLog {
    @Resource
    private SysLoginLogMapper loginLogMapper;

    @Async("taskExecutor")
    public void loginLog(HttpServletRequest request, String loginId, String status, String message) {
        log.info(">>>>>>>>>>>>>>记录登录的日志<<<<<<<<<<<<<<<<<<<<");
        String ip = IpUtils.getIpAddr(request);
        String address = AddressUtils.getRealAddressByIP(ip);
        final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        SysLoginLogEntity logEntity = SysLoginLogEntity.builder()
                .loginId(loginId)
                .status(status)
                .message(message)
                .creatorIp(ip)
                .creatorAddress(address)
                .browser(browser)
                .operatingSystem(os)
                .build();
        loginLogMapper.insert(logEntity);
    }
}
